import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-sys-role-edit',
  templateUrl: './edit.component.html'
})
export class SysRoleEditComponent implements OnInit {
  record: any = {};
  i: any;
  validateForm: FormGroup;

  controlsConfig = {
    ID: [null, null],
    name: ['', [Validators.required]],
    alias: ['', [Validators.required]],
    desc: ['', []],
    status: [1, []],
    company_id: ['', [Validators.required]]
  };
  companies = [];

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient, private fb: FormBuilder) {
    this.validateForm = this.fb.group(this.controlsConfig);
    this.loadDataFromServer();
  }

  loadDataFromServer() {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companies = res.data;
    });
  }

  ngOnInit(): void {
    if (this.record.ID > 0) {
      this.http.get(`api/role/${this.record.ID}`).subscribe(res => {
        this.i = res.data;
        this.validateForm.patchValue(res.data);
      });
    }
  }

  save(value: any): void {
    if (!value.ID) {
      this.http.post(`api/role`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.msgSrv.success(res.msg);
        this.modal.close(true);
      });
    } else {
      this.http.put(`api/role/${this.record.ID}`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.msgSrv.success(res.msg);
        this.modal.close(true);
      });
    }
  }

  close(): void {
    this.modal.destroy();
  }
}
